import math

from ConfigurationData import letNum
from ConfigurationData import ConfigurationData


def execute_leveraged_trade(client, symbol, leverage ,side):
    """执行带杠杆的交易操作。

    :param client: Binance客户端实例。
    :param symbol: 交易对。
    :param leverage: 杠杆倍数。
    :param balance_percentage: 使用的账户余额百分比。
    """
    # 首先设置杠杆
    try:
        client.futures_change_leverage(symbol=symbol, leverage=leverage)
        print(f"{leverage}倍{symbol}:")
    except Exception as e:
        print(f"Error setting leverage for {symbol}: {e}")
        return

    # 确定交易数量
    try:
        # 获取账户余额
        balance_info = client.futures_account_balance()
        balance_usdt = float(next(item for item in balance_info if item['asset'] == 'USDT')['balance'])

        # 计算用于交易的USDT数量（指定百分比的账户余额）
        usdt_to_use = balance_usdt * 0.8

        # 获取当前市价
        latest_price = float(client.futures_symbol_ticker(symbol=symbol)['price'])

        # 获取交易对数量精度
        info = client.futures_exchange_info()
        symbol_info = next(item for item in info['symbols'] if item['symbol'] == symbol)
        quantity_precision = symbol_info['quantityPrecision']

        # 计算可以购买的资产数量
        quantity = (usdt_to_use * leverage) / latest_price
        quantity = round(quantity, quantity_precision)

        # 创建市价订单
        order = client.futures_create_order(
            symbol=symbol,
            side=side,
            type='MARKET',
            quantity=quantity
        )

        # 查询订单详情
        order_details = client.futures_get_order(symbol=symbol, orderId=order['orderId'])

        # 从订单详情中提取执行价格
        if 'avgPrice' in order_details:
            execution_price = float(order_details['avgPrice'])
        else:
            # 如果没有找到执行价格，需要处理这种异常情况
            print("无法从订单详情中找到执行价格")
            execution_price = None

        # 如果能够获取到执行价格，那么基于这一价格计算止损价格
        if execution_price:
            stop_loss_price = execution_price * (1 +(letNum*0.001)) if side == 'SELL' else execution_price * (1 -(letNum*0.001))

        # 创建止单
        # 注意：确保你的止损价格符合交易所的价格限制规则
        stop_order = client.futures_create_order(
            symbol=symbol,
            side='SELL' if side == 'BUY' else 'BUY',
            type='STOP_MARKET',
            quantity=quantity,
            stopPrice=str(math.ceil(stop_loss_price * 10 ** 2) / 10 ** 2),  # 向上舍入到合符规则的价格精度
            timeInForce='GTC'  # 订单时效性，例如：GTC（一直有效直到完成）
        )

        print("已按照市场价下单，止损单已设置")

        #下单详情：需要查看的时候打开
        #print("Order successful:", order)
    except Exception as e:
        print(f"Error during operation: {e}")
